/*
 * Copyright (C) 2019 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.sj.parksdk.activity;

import android.annotation.SuppressLint;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MenuItem;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.sj.parksdk.R;
import com.sj.parksdk.R2;
import com.sj.parksdk.core.BaseActivity;
import com.sj.parksdk.core.BaseFragment;
import com.sj.parksdk.core.http.subscriber.TipRequestSubscriber;
import com.sj.parksdk.fragment.main.FragmentMain;
import com.sj.parksdk.fragment.park.FragmentPark;
import com.sj.parksdk.fragment.profile.ProfileFragment;
import com.sj.parksdk.net.http.ApiHelper;
import com.sj.parksdk.net.manager.TokenManager;
import com.sj.parksdk.net.result.databean.Data_Token;
import com.sj.parksdk.setting.CommonKey;
import com.sj.parksdk.utils.MMKVUtils;
import com.sj.parksdk.utils.Utils;
import com.sj.parksdk.utils.XToastUtils;
import com.sj.parksdk.utils.bdlocation.LocateState;
import com.sj.parksdk.utils.bdlocation.LocatedInfo;
import com.sj.parksdk.utils.bdlocation.LocationService;
import com.sj.parksdk.utils.bdlocation.OnBDLocationListener;
import com.sj.parksdk.utils.bdlocation.OnLocationListener;
import com.sj.parksdk.utils.minterface.HomeInterface;
import com.sj.parksdk.widget.ViewPageNoScroll;
import com.xuexiang.xaop.annotation.Permission;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xhttp2.logs.HttpLog;
import com.xuexiang.xhttp2.request.CustomRequest;
import com.xuexiang.xui.adapter.FragmentAdapter;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.utils.StatusBarUtils;
import com.xuexiang.xui.widget.statelayout.StatefulLayout;
import com.xuexiang.xutil.common.CollectionUtils;

import butterknife.BindView;

import static com.sj.parksdk.setting.MPermissionConsts.ACCESS_NETWORK_STATE;
import static com.sj.parksdk.setting.MPermissionConsts.ACCESS_WIFI_STATE;
import static com.sj.parksdk.setting.MPermissionConsts.INTERNET;
import static com.xuexiang.xaop.consts.PermissionConsts.CAMERA;
import static com.xuexiang.xaop.consts.PermissionConsts.LOCATION;
import static com.xuexiang.xaop.consts.PermissionConsts.STORAGE;

/**
 * @author tongmm
 * @since 2019-07-07 23:53
 */
public class ParkSdkMainActivity extends BaseActivity implements ViewPager.OnPageChangeListener, BottomNavigationView.OnNavigationItemSelectedListener {

    @BindView(R2.id.view_pager) ViewPageNoScroll viewPager;
    @BindView(R2.id.ll_state) StatefulLayout llState;
    /**
     * 底部导航栏
     */
    @BindView(R2.id.bottom_navigation) BottomNavigationView bottomNavigation;
    private String[] mTitles;

    private OnBDLocationListener mBDListener;

    private FragmentAdapter<BaseFragment> adapterFragment;

    @Override
    protected int getLayoutId() {
        return R.layout.parksdk_activity_main;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @Permission({LOCATION, CAMERA, STORAGE, ACCESS_NETWORK_STATE, INTERNET, ACCESS_WIFI_STATE})
    private void init() {
        llState.showLoading();
        boolean isAgree = MMKVUtils.getBoolean(CommonKey.KEY_AGREE_PRIVACY, false);
        if (isAgree) {
            initVisitToken();
        } else {
            Utils.showPrivacyDialog(this, (sDialog) -> {
                sDialog.dismiss();
                MMKVUtils.put(CommonKey.KEY_AGREE_PRIVACY, true);
                initVisitToken();
            });
        }
    }

    @SuppressLint("CheckResult")
    private void initVisitToken() {
        CustomRequest request = XHttp.custom();
        request.apiCall(ApiHelper.getInstance(request).anonymous())
                .subscribeWith(new TipRequestSubscriber<Data_Token>() {
                    @Override
                    protected void onSuccess(Data_Token data) {
                        TokenManager.getInstance().setVisitToken(data.getAccess_token());
                        TokenManager.getInstance().setSign(data.getToken_type());
                        HttpLog.e("访客token刷新成功：" + data.getAccess_token());

                        initBDLocation();
                        refreshToken();
                    }

                    @Override
                    public void onError(ApiException e) {
                        llState.showError("服务加载失败", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                init();
                            }
                        });
                    }
                });

    }

    private void refreshToken() {
        if (!TokenManager.getInstance().isUserLogined()) {
            llState.showContent();
            initViews();
            initListeners();
            return;
        }
        onRefreshToken();
    }

    @SuppressLint("CheckResult")
    private void onRefreshToken() {
        CustomRequest request = XHttp.custom();
        request.apiCall(ApiHelper.getInstance(request).refreshToken()).subscribeWith(new TipRequestSubscriber<Data_Token>() {
            @Override
            protected void onSuccess(Data_Token data) {
                llState.showContent();

                TokenManager.getInstance().setToken(data.getAccess_token());
                TokenManager.getInstance().setSign(data.getToken_type());
                TokenManager.getInstance().setTokenExpiresOn(data.getExpires_on());
                HttpLog.e("token刷新成功：" + data.getAccess_token());
                initViews();
                initListeners();
            }

            @Override
            public void onError(ApiException e) {
                super.onError(e);
                HttpLog.e("token刷新失败：");
                llState.showContent();
                initViews();
                initListeners();
            }
        });
    }

    private void initBDLocation() {
        mBDListener = new OnBDLocationListener();
        mBDListener.setOnLocationListener(locationChangeListener);
    }

    @Override
    protected void initStatusBarStyle() {
        StatusBarUtils.initStatusBarStyle(this, true);
    }

    @Override
    protected boolean isSupportSlideBack() {
        return false;
    }

    private void initViews() {
        mTitles = ResUtils.getStringArray(R.array.park_home_titles);
        //主页内容填充
        FragmentMain main = new FragmentMain();
        main.setmHomeInterface(mHomeInterface);
        BaseFragment[] fragments = new BaseFragment[]{
                main,
                new FragmentPark(),
                new ProfileFragment()
        };
        adapterFragment = new FragmentAdapter<>(getSupportFragmentManager(), fragments);
        viewPager.setOffscreenPageLimit(mTitles.length - 1);
        viewPager.setAdapter(adapterFragment);
        initBootomTab();

    }

    private void initBootomTab() {
        int[][] states = new int[][]{
                new int[]{-android.R.attr.state_checked},
                new int[]{android.R.attr.state_checked}
        };
        int[] colors = new int[]{ResUtils.getColor(R.color.color_9), ResUtils.getColor(R.color.color_3)};
        ColorStateList csl = new ColorStateList(states, colors);
        bottomNavigation.setItemIconTintList(null);
        bottomNavigation.setItemTextColor(csl);
    }

    protected void initListeners() {
        //主页事件监听
        viewPager.addOnPageChangeListener(this);
        bottomNavigation.setOnNavigationItemSelectedListener(this);
    }

    //=============ViewPager===================//

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int position) {
        MenuItem item = bottomNavigation.getMenu().getItem(position);
        item.setChecked(true);
        if (position == 0) StatusBarUtils.setStatusBarDarkMode(this);
        else {
            StatusBarUtils.setStatusBarLightMode(this);
        }
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    //================Navigation================//

    /**
     * 底部导航栏点击事件
     *
     * @param menuItem
     * @return
     */
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        int index = CollectionUtils.arrayIndexOf(mTitles, menuItem.getTitle());
        if (index != -1) {
            viewPager.setCurrentItem(index, true);
            return true;
        }
        return false;
    }

    private HomeInterface mHomeInterface = new HomeInterface() {

        @Override
        public void startLocat() {
            LocationService.start(mBDListener);
        }

        @Override
        public void refreshLocation() {
            LocationService.stop(mBDListener);
            initBDLocation();
            LocationService.start(mBDListener);
        }

        @Override
        public void stopLocation() {
            LocationService.stop(mBDListener);
        }
    };

    private OnLocationListener locationChangeListener = new OnLocationListener() {
        @Override
        public void onLocationChanged(LocatedInfo location, int state) {

            if (LocateState.FAILURE == state) {
                XToastUtils.error(ResUtils.getString(R.string.toast_locat_error));
                mHomeInterface.stopLocation();
                return;
            }
            if (LocateState.SUCCESS == state) {
                Message msg = new Message();
                msg.obj = location;
                msg.what = 1;
                locHandler.sendMessage(msg);
            }
        }
    };

    private void updateFragmentLocationData(LocatedInfo locationInfo) {
        if (adapterFragment == null) return;
        FragmentMain fmm = (FragmentMain) adapterFragment.getItem(0);
        if (fmm != null) fmm.updataLocation(locationInfo);
        FragmentPark fmp = (FragmentPark) adapterFragment.getItem(1);
        if (fmp != null) fmp.updateLocData(locationInfo);
    }

    @SuppressLint("HandlerLeak")
    private Handler locHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    LocatedInfo location = (LocatedInfo) msg.obj;
                    updateFragmentLocationData(location);
                    break;
                default:
                    throw new IllegalStateException("Unexpected value: " + msg.what);
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        if (!TokenManager.getInstance().onRefreshLogin()) return;
        if (adapterFragment == null || adapterFragment.getFragmentList() == null || adapterFragment.getFragmentList().size() != 3)
            return;
        FragmentMain main = (FragmentMain) adapterFragment.getFragmentList().get(0);
        ProfileFragment my = (ProfileFragment) adapterFragment.getFragmentList().get(2);
        if (main != null) {
            main.initDeraultCar();
        }
        if (my != null) {
            my.initUserInfo();
        }
        TokenManager.getInstance().refreshLoginState(false);
    }

//    /**
//     * 菜单、返回键响应
//     */
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            ClickUtils.exitBy2Click(2000, this);
//        }
//        return true;
//    }
//
//    @Override
//    public void onRetry() {
//        XToastUtils.toast("再按一次退出程序");
//    }
//
//    @Override
//    public void onExit() {
//        XUtil.exitApp();
//    }


//    private class   MyLocationListener extends BDAbstractLocationListener{
//
//        @Override
//        public void onReceiveLocation(BDLocation bdLocation) {
//
//        }
//    }


}
